<template>
  <div class="news-container">
    <el-card class="news-card">
      <template #header>
        <div class="card-header">
          <span>新闻资讯</span>
        </div>
      </template>
      
      <el-table :data="newsList" style="width: 100%">
        <el-table-column prop="title" label="标题" width="300">
          <template #default="{ row }">
            <router-link :to="`/news/${row.id}`" class="news-title">
              {{ row.title }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="summary" label="摘要" />
        <el-table-column prop="createTime" label="发布时间" width="180" />
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

interface NewsItem {
  id: number
  title: string
  summary: string
  content: string
  createTime: string
}

interface ApiResponse<T> {
  code: number
  message: string
  data: T
}

interface PageResponse<T> {
  records: T[]
  total: number
  size: number
  current: number
}

const newsList = ref<NewsItem[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const fetchNewsList = async () => {
  try {
    const response = await request.get<ApiResponse<PageResponse<NewsItem>>>('/news/list', {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    if (response.data && response.data.data) {
      newsList.value = response.data.data.records
      total.value = response.data.data.total
    }
  } catch (error) {
    ElMessage.error('获取新闻列表失败')
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchNewsList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchNewsList()
}

onMounted(() => {
  fetchNewsList()
})
</script>

<style scoped>
.news-container {
  padding: 20px;
}

.news-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.news-title {
  color: #409EFF;
  text-decoration: none;
}

.news-title:hover {
  text-decoration: underline;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>